import sys
import binascii
from scapy.all import *


DST = '192.168.1.167'
# VM_SRC = '10.211.55.3'
# VM_SRC = '192.168.1.110'
# LAP_SRC = '192.168.1.109'

def big_small_endian_convert(big_endian_str):
    return int(binascii.hexlify(binascii.unhexlify(big_endian_str)[::-1]), base = 16)


def get_payload_from_pcap(filename):
    pkts = rdpcap(filename)

    # if 'vm' in filename:
    #     SRC = VM_SRC
    # else:
    #     SRC = LAP_SRC
    init = 0
    init_time = 0
    with open(f'{filename}.scapy.csv', 'w') as f:
        f.write(f't_ms,seq\n')
        for pkt in pkts:
            if init == 0:
                init_time = int(pkt.time * 1000)
                init = 100

            if 'IP' in pkt:
                # if pkt['IP'].dst == DST and pkt['IP'].src == SRC:
                if pkt['IP'].dst == DST:
                    if 'UDP' in pkt:
                        if 'Raw' in pkt['UDP']:
                            payload = hexdump(pkt['UDP']['Raw'].load, dump = True)[6:17].replace(' ', '')
                            if len(payload) == 8:
                                seq = big_small_endian_convert(payload)
                                if seq != 4294967295:
                                    t_ms = int(pkt.time * 1000) - init_time
                                    f.write(f'{t_ms},{seq}\n')
                            else:
                                print('Warning payload:', payload)


if __name__ == '__main__':
    get_payload_from_pcap(sys.argv[1])